<!--
 /**
 * Author: hongChengHao
 * Date: 2022-07-30 17:19
 * Desc: 下载二维码
 */
-->
<template>
  <view class="qr-code">
    <!--#ifdef MP-ALIPAY -->
    <canvas
      v-if="!isComplete"
      id="canvasQr"
      :style="
        'width:' +
        canvasWidth +
        'px;height:' +
        canvasHeight +
        'px;position:absolute;left:-99999px;'
      "
    ></canvas>
    <!-- #endif -->
    <!--#ifdef MP-WEIXIN || H5 || MP-TOUTIAO -->
    <canvas
      v-if="!isComplete"
      canvas-id="canvasQr"
      :style="
        'width:' +
        canvasWidth +
        'px;height:' +
        canvasHeight +
        'px;position:absolute;left:-99999px;'
      "
    ></canvas>
    <!-- #endif -->
    <view class="qr-code__content" v-if="isComplete">
      <view class="qr-code__img">
        <image :src="tempFilePath" style="height: 100%; width: 100%"></image>
      </view>
      <view class="mt50 tc">{{ canvasWidth }}*{{ canvasHeight }}</view>
      <view class="qr-code__des">
        <!-- #ifdef H5 -->
        <view @click="saveImg">{{
          isWxBrowswer ? '长按二维码保存到相册' : '保存图片'
        }}</view>
        <!-- #endif -->
        <!--#ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO-->
        <u-button @click="saveImg">保存图片</u-button>
        <!--#endif -->
      </view>
    </view>
  </view>
</template>
<script>
  // import { getEvn } from '@/utils/h5/handleEvn.js'
  // #ifdef H5
  import jrQrcode from 'jr-qrcode'
  // #endif
  import { locPosterInfo } from '@/utils/locStore/data'
  export default {
    name: 'QrCode',
    data() {
      return {
        type: '',
        qrUrl: '',
        isComplete: false,
        tempFilePath: '',
        canvasWidth: 480,
        canvasHeight: 480,
        logoWidth: 80,
        logoHeight: 80,
        cxt: null,
        //  #ifdef  H5
        isWxBrowswer: this.$tools.isWxBrowswer()
        // #endif
      }
    },
    async onLoad(options) {
      this.qrUrl = options.qrUrl

      // #ifdef H5
      const opt = locPosterInfo.get()
      this.qrUrl = opt.qrUrl
      this.createQrUrl()
      // #endif

      this.type = options.type || '1'

      if (this.type === '2') {
        this.canvasWidth = 1280
        this.canvasHeight = 1280
        this.logoWidth = 200
        this.logoHeight = 200
      }
    },
    onReady() {
      this.ctx = uni.createCanvasContext('canvasQr', this)
      console.log('ctx', this.ctx)
      this.drawposter()
    },
    methods: {
      //生成H5二维码url
      createQrUrl() {
        const imgBase64 = jrQrcode.getQrBase64(this.qrUrl, {
          width: this.canvasWidth,
          height: this.canvasHeight
        })
        this.qrUrl = imgBase64
      },
      // 开始绘画
      async drawposter() {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        console.log('drawposter', this.canvasWidth)
        await this.drawWebImg({
          url: this.qrUrl,
          x: 0,
          y: 0,
          width: this.canvasWidth,
          height: this.canvasWidth
        })
        // #ifndef MP-WEIXIN
        let logo = this.$auth.getLocBaseSet().logo
        if (logo.indexOf('https://images.zmaxfilm.com') > -1) {
          logo = ''
        }
        if (logo) {
          await this.drawWebImg({
            url: logo,
            x: this.canvasWidth / 2 - this.logoWidth / 2,
            y: this.canvasWidth / 2 - this.logoHeight / 2,
            width: this.logoWidth,
            height: this.logoHeight
          })
        }

        // #endif
        this.tempFilePath = await this.saveCanvs()
        this.isComplete = true
        uni.hideLoading()
      },
      // 画图
      drawWebImg(conf) {
        return new Promise((resolve, reject) => {
          console.log('downloadFile', conf)
          uni.downloadFile({
            url: conf.url,
            success: (res) => {
              console.log('success', res, this.ctx)
              // console.log('this.ctx.drwaImage:', this.ctx.drwaImage)
              this.ctx.drawImage(
                res.tempFilePath,
                conf.x,
                conf.y,
                conf.width ? conf.width : '',
                conf.height ? conf.height : ''
              )
              this.ctx.draw(true, () => {
                console.log('success draw')
                resolve()
              })
            },
            fail: (err) => {
              console.log('fail', err)
              reject(err, '画图出错')
            }
          })
        })
      },
      // canvas 转 图片
      saveCanvs() {
        console.log('drawposter')
        return new Promise((resolve, reject) => {
          uni.canvasToTempFilePath(
            {
              x: 0,
              y: 0,
              canvasId: 'canvasQr',
              success: (res) => {
                console.log('canvasToTempFilePath success', res)
                resolve(res.tempFilePath)
              },
              fail: (err) => {
                console.log('canvasToTempFilePath fail', err)
                uni.hideLoading()
                reject(err)
              }
            },
            this
          )
        })
      },

      saveToPhoto() {
        uni.saveFile({
          tempFilePath: this.tempFilePath,
          success: (res) => {
            uni.saveImageToPhotosAlbum({
              //保存图片到系统相册。
              filePath: res.savedFilePath, //图片文件路径
              success: function () {
                uni.showToast({
                  title: '图片保存成功',
                  icon: 'none'
                })
              },
              fail: async (e) => {
                console.log(e)
                uni.showToast({
                  title: '图片保存失败',
                  icon: 'none'
                })
                this.isComplete = false
                this.ctx = uni.createCanvasContext('canvasQr', this)
                this.drawposter()
              }
            })
          }
        })
      },

      // 保存图片到相册
      saveImg() {
        this.$auth.getShareCount().then(() => {
          // #ifdef H5
          if (this.isWxBrowswer) {
            return
          } else {
            const Url = this.tempFilePath //图片路径，也可以传值进来
            const blob = new Blob([''], { type: 'application/octet-stream' }) //二进制大型对象blob
            const url = URL.createObjectURL(blob) //创建一个字符串路径空位
            const a = document.createElement('a') //创建一个 a 标签
            a.href = Url //把路径赋到a标签的href上
            a.download = Url.replace(/(.*\/)*([^.]+.*)/gi, '$2').split('?')[0]
            const e = new MouseEvent(
              'click',
              (true,
              false,
              window,
              0,
              0,
              0,
              0,
              0,
              false,
              false,
              false,
              false,
              0,
              null)
            )
            a.dispatchEvent(e)
            URL.revokeObjectURL(url)
          }
          // #endif
          // #ifdef  MP-ALIPAY
          this.saveToPhoto()
          // #endif
          // #ifdef MP-WEIXIN
          uni.getSetting({
            success: (setRes) => {
              if (!setRes.authSetting['scope.writePhotosAlbum']) {
                uni.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success: () => {
                    this.saveToPhoto()
                  },
                  fail: () => {
                    //授权失败
                    uni.showModal({
                      title: '您已拒绝获取相册权限',
                      content: '是否进入权限管理，调整授权？',
                      success: (res) => {
                        if (res.confirm) {
                          //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                          uni.openSetting({
                            success: (res) => {
                              console.log(res.authSetting)
                            }
                          })
                        } else if (res.cancel) {
                          return uni.showToast({
                            title: '已取消！'
                          })
                        }
                      }
                    })
                  }
                })
              } else {
                this.saveToPhoto()
              }
            }
          })
          console.log('this.tempFilePath', this.tempFilePath)
          // #endif
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .qr-code {
    overflow: hidden;
    &__content {
      box-sizing: border-box;
      padding-top: 100upx;
      width: 100%;
      height: 100vh;
    }
    &__img {
      margin: 0 auto;
      width: 600upx;
      height: 600upx;
    }
    &__des {
      width: 100%;
      position: fixed;
      bottom: 0;
      text-align: center;
      // #ifdef H5
      bottom: 30upx;
      // #endif
    }
  }
</style>
